package com.skplanet.oneplusonewindow.moim;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;

import android.app.Activity;
import android.os.Message;

public class SocketChat {
	
	private static Activity activity;
	private Socket socket;
	private DataOutputStream out;
	private String name;
	private Thread receiver;
	
	private StringBuilder content = new StringBuilder("");
	
	public SocketChat(Activity p, String name) {
		SocketChat.activity = p;
		System.out.println("try");
		try {
			System.out.println("try");
			String serverIp = "27.102.204.51";
			socket = new Socket(serverIp, 7777);
			System.out.println("서버에 연결되었습니다.");
			
			this.name = name;
			out = new DataOutputStream(socket.getOutputStream());
			out.writeInt(user.getInstance().getMiom_id());
			out.writeUTF(name);
			receiver = new ClientReceiver(socket);
			((ClientReceiver) receiver).SetSocket(this);
			receiver.start();
		} catch(ConnectException ce) {
			ce.printStackTrace();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	public void close() {
		try {
			((ClientReceiver)receiver).close();
			receiver.join();
			out.close();
			socket.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
	}
	
	public Activity getActivity() {
		return SocketChat.activity;
	}
	public StringBuilder getContent() {
		return this.content;
	}
	public void setContent(String content) {
		this.content = new StringBuilder(content);
	}

	public void send(String content) {

		try {

			out.writeUTF("[" + name + "]" + content);
			
		} catch(IOException e) {}
	
	}

	static class ClientReceiver extends Thread {
		Socket socket;
		DataInputStream in;
		SocketChat mo;

		ClientReceiver(Socket socket) {
			this.socket = socket;
			try {
				in = new DataInputStream(socket.getInputStream());
			} catch(IOException e) {}
		}
		
		public void SetSocket(SocketChat mo) {
			this.mo = mo;
		}
		
		public void close() {
			try {
				in.close();
				socket.close();
				in = null;
			} catch(Exception e) {
				
			}
		}

		public void run() {
			System.out.println("test");
			while(in != null) {
				try {
					mo.setContent(in.readUTF());
					Message msg = new Message();
					msg.what = 0;
					((MainActivity)mo.getActivity()).handler.sendMessage(msg);
				} catch(IOException e) {}
			}
		}
	}
}
